import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { TouchableOpacity, Text, StyleSheet, ActivityIndicator } from 'react-native';
import { Icon } from 'react-native-elements';
import { toast, primaryColor, uploadImage, executor } from '../utils';
import { BagCheckQuery } from '../graphql';
import moment from 'moment';

const styles = StyleSheet.create({
  spinner: {
    marginRight: 16
  },
  button: {
    color: primaryColor,
    fontSize: 17,
    padding: 14 
  },
  icon: {
    marginRight: 16,
    color: primaryColor,
    fontSize: 16
  },
});

class BagCheckButton extends Component {
  state = {}
  onSubmit = () => {
    const { selects } = this.props.navigation.state.params||{};
    if (!selects||selects.length===0) return toast('Please select bags');

    executor(this.props.checkLaundryBags)
      .then(({res}) => {
        if (res) {
          toast('Bags checked');
          this.props.onSuccess();
        }
        this.setState({processing: false});
      });
    this.setState({processing: true});
  }
  render() {
    const { processing } = this.state;

    return processing?<ActivityIndicator style={styles.spinner} color={primaryColor}/>:
      <TouchableOpacity onPress={this.onSubmit}>
        <Text style={styles.icon}>Check</Text>
      </TouchableOpacity>;
  }
}

export default compose(
  graphql(gql`
    mutation checkLaundryBags($laundryBags:[String]!) {
      checkLaundryBags(laundryBags:$laundryBags)
    }
  `, {
    name: 'checkLaundryBags',
    props: ({ownProps:{navigation:{state:{params}}}, checkLaundryBags}) => {
      return {
        checkLaundryBags: () => checkLaundryBags({
          variables: {
            laundryBags: params&&params.selects
          },
          refetchQueries: [{
            query: BagCheckQuery,
            variables: { 
              date: (params&&params.date)||moment([moment().year(), moment().month(), moment().date()]).subtract(1,'days').toDate().toString()
            },
          }]
        })
      };
    }
  })
)(BagCheckButton);